package com.kll.carolinehmibiz.base.net.exception;

import android.accounts.NetworkErrorException;
import android.net.ParseException;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

/**
 * Created by zlcai
 * 22:15
 */

public class BaseExceptionEngine {

    public static final String NOT_FOUND_STR = "404 Not Found";

    public static ServerException handleException(Throwable e) {
        ServerException ex;
        if (e instanceof JSONException || e instanceof ParseException) {
            ex = new ServerException(e, ResultCode.BASE_PARSE_ERROR);
            ex.setMessage(getMessage(ResultCode.BASE_PARSE_ERROR));
            return ex;
        } else if (e instanceof UnknownHostException || e instanceof ConnectException
                || e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException) {
            ex = new ServerException(e, ResultCode.BASE_NETWORK_ERROR);
            ex.setMessage(getMessage(ResultCode.BASE_NETWORK_ERROR));
            return ex;
        } else if (e instanceof HttpException) {
            if (NOT_FOUND_STR.equals(e.getMessage())) {
                ex = new ServerException(e, ResultCode.BASE_NOT_FOUND);
                ex.setMessage(getMessage(ResultCode.BASE_NOT_FOUND));
            } else {
                ex = new ServerException(e, ResultCode.BASE_NETWORK_ERROR);
                ex.setMessage(getMessage(ResultCode.BASE_NETWORK_ERROR));
            }
            return ex;
        } else if (e instanceof NetworkErrorException) {
            ex = new ServerException(e, ResultCode.BASE_NETWORK_DISCONNECT);
            ex.setMessage(getMessage(ResultCode.BASE_NETWORK_DISCONNECT));
            return ex;
        } else {
            ex = new ServerException(e, ResultCode.BASE_UNKONW);
            ex.setMessage(getMessage(ResultCode.BASE_UNKONW));
            return ex;
        }
    }

    private static String getMessage(int code) {
        return ResultCode.GCS_RESULT_MESSAGE.get(code);
    }

}